package com.wie.staffhubpro.service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

public class IpUtils {

    // 可信代理IP段（支持CIDR表示法）
    private static final List<String> TRUSTED_PROXIES = Arrays.asList(

    );

    // IP格式校验正则
    private static final Pattern IPV4_PATTERN = Pattern.compile(
            "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");
    private static final Pattern IPV6_STD_PATTERN = Pattern.compile(
            "^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$");
    private static final Pattern IPV6_HEX_COMPRESSED_PATTERN = Pattern.compile(
            "^((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)$");

    public static String getClientIp(HttpServletRequest request) {
        // 优先从标准头获取
        String clientIp = getClientIpFromXffHeader(request);
        if (clientIp != null) return clientIp;

        // 备选头（根据实际情况选择）
        clientIp = request.getHeader("X-Real-IP");
        if (isValidIp(clientIp)) return clientIp;

        clientIp = request.getHeader("Proxy-Client-IP");
        if (isValidIp(clientIp)) return clientIp;

        clientIp = request.getHeader("WL-Proxy-Client-IP");
        if (isValidIp(clientIp)) return clientIp;

        // 都没有则返回直接连接的客户端IP
        return request.getRemoteAddr();
    }

    private static String getClientIpFromXffHeader(HttpServletRequest request) {
        String xffHeader = request.getHeader("X-Forwarded-For");
        if (xffHeader == null || xffHeader.isEmpty()) {
            return null;
        }

        // 按逗号分割并清理空格
        String[] ips = xffHeader.trim().split(",");
        List<String> ipList = new ArrayList<>(ips.length);
        for (String ip : ips) {
            String trimmedIp = ip.trim();
            if (isValidIp(trimmedIp)) {
                ipList.add(trimmedIp);
            }
        }

        // 从后向前遍历，跳过所有可信代理
        for (int i = ipList.size() - 1; i >= 0; i--) {
            String currentIp = ipList.get(i);
            if (!isTrustedProxy(currentIp)) {
                return currentIp; // 找到第一个非可信代理IP
            }
        }

        // 如果所有IP都是可信代理，返回最后一个（最接近服务器的代理）
        return !ipList.isEmpty() ? ipList.get(ipList.size() - 1) : null;
    }

    private static boolean isValidIp(String ip) {
        if (ip == null || ip.isEmpty()) return false;
        // 检查是否为IPv4
        if (IPV4_PATTERN.matcher(ip).matches()) return true;
        // 检查是否为IPv6标准格式
        if (IPV6_STD_PATTERN.matcher(ip).matches()) return true;
        // 检查是否为IPv6压缩格式
        return IPV6_HEX_COMPRESSED_PATTERN.matcher(ip).matches();
    }

    private static boolean isTrustedProxy(String ip) {
        for (String trustedProxy : TRUSTED_PROXIES) {
            if (trustedProxy.contains("/")) {
                // CIDR格式网段
                String[] parts = trustedProxy.split("/");
                String baseIp = parts[0];
                int prefix = Integer.parseInt(parts[1]);

                if (isIpInCidrRange(ip, baseIp, prefix)) {
                    return true;
                }
            } else {
                // 单个IP
                if (trustedProxy.equals(ip)) {
                    return true;
                }
            }
        }
        return false;
    }

    private static boolean isIpInCidrRange(String ip, String baseIp, int prefix) {
        // 此处应有CIDR范围检查实现
        // 简化版：实际生产中建议使用成熟库如Apache Commons Net
        return false;
    }

}
